<?php
/**
 * ProductController for managing products
 *
 * @author guzhi
 * @since 2009-03-25
 */

require_once BaseUtil::getModulePath("base")  .  '/controllers/BaseController.php';
require_once BaseUtil::getModulePath("inventory")  .  '/forms/ProductForm.php';
require_once BaseUtil::getModulePath("inventory")  .  '/forms/AttributeForm.php';
require_once BaseUtil::getModulePath("inventory")  .  '/forms/ItemForm.php';
require_once BaseUtil::getModulePath("inventory")  .  '/services/ProductService.php';
require_once BaseUtil::getModulePath("inventory")  .  '/services/CategoryService.php';
require_once BaseUtil::getModulePath("inventory")  .  '/constants/InventoryConstant.php';
require_once BaseUtil::getModulePath("metadata")  .  '/constants/MetadataConstant.php';
require_once   BaseUtil::getModulePath("common")  .  '/services/SshService.php';
require_once 'core/Thumbnail.php';

class Inventory_ProductController extends BaseController {
    
    private $_enableSsh = false;
    
    public function init() {
        parent::init();
        $this->view->script = array('lib/ui.dialog.js','lib/dhtmlXCommon.js','lib/dhtmlXTree.js','lib/dhtmlXTreeExtend.js','inventory.js');
        $ssh_config = Zend_Registry::get("ssh_impl");
        if ($ssh_config["enable"] == "true")
        {
            $this->_enableSsh = true;
        }
        else
        {
            $this->_enableSsh = false;
        }
    }

    public function indexAction() {
        $productService = new ProductService();
        $products = $productService->getProducts($this->view, $_POST);
        $this->view->products = $products;
    }

    public function selectAction(){
        $productService = new ProductService();
        $sets = $productService->getSets();
        $this->view->sets = $sets;
    }

    public function addAction() {
        $setId = $this->_getParam("set");
        $productService = new ProductService();
        $departments = $productService->getDepartments();
        //$relates = $productService->getRelates();
        $productForm = new ProductForm($departments[1]);
        $categoryService = new CategoryService();
        $categoriesXml = $categoryService->getAllCategoriesXml();
        //metadata set
        $metadataSet = $productService->getSetById($setId);
        //set default rule
        $productForm->getElement("chequeRule")->setValue($metadataSet['default_cheque_rule']);
        $productForm->getElement("priceRule")->setValue($metadataSet['default_price_rule']);
        $productForm->getElement("shipRule")->setValue($metadataSet['default_ship_rule']);
        $productForm->getElement("relatedRule")->setValue($metadataSet['default_related_rule']);
        //product metadata
        $productMetadatas = $productService->getMetadataBySet($setId, 1);
        //item metadata
        $itemMetadatas = $productService->getMetadataBySet($setId, 2);
        
        $this->view->form = $productForm;
        $this->view->categoryXml = $categoriesXml;
        $this->view->metadataSet = $metadataSet;
        $this->view->productMetadatas = $productMetadatas;
        $this->view->itemMetadatas = $itemMetadatas;
        $this->view->metadataSetId = $setId;
    }

    public function subaddAction() {       
        $productService = new ProductService();
        $categoryService = new CategoryService();
        $departments = $productService->getDepartments();
        //$relates = $productService->getRelates();
        $productForm = new ProductForm($departments[1]);
        if(!$productForm->isValid($_POST)) {
            $categoriesXml = $categoryService->getAllCategoriesXml();           
            $setId = trim($_POST['metadataSetId']);
            //metadata set
            $metadataSet = $productService->getSetById($setId);
            //product metadata
            $productMetadatas = $productService->getMetadataBySet($setId, 1);
            //item metadata
            $itemMetadatas = $productService->getMetadataBySet($setId, 2);
            $this->view->metadataSet = $metadataSet;
            $this->view->productMetadatas = $productMetadatas;
            $this->view->itemMetadatas = $itemMetadatas;           
            $this->view->categoryXml = $categoriesXml;
            $this->view->form = $productForm;
            $this->view->metadataSetId = $setId;
            return $this->render('add');
        }
        $productId = $productService->addProduct($productForm,$_POST);
        if(empty($productId)){
            $this->_redirector->gotoUrl("inventory/product");
        }else{
        	$this->_redirector->gotoUrl("inventory/product/edit/id/" . $productId);
        }

    }

    public function editAction() {
        $productId = $this->_getParam('id');
        $productService = new ProductService();
        $product = $productService->getProductById($productId);
        $departments = $productService->getDepartments();
        $productItems = $productService->getItemsByProduct($productId);
        //metadata
        $setId = $product['metadata_set_id'];
        //metadata set
        $metadataSet = $productService->getSetById($setId);
        //product metadata
        $productMetadatas = $productService->getMetadataBySet($setId, 1);
        //item metadata
        $itemMetadatas = $productService->getMetadataBySet($setId, 2);
        //product metadata value
        $productMetadataValues = $productService->getProductMetatdataValue($productId);
        //$relates = $productService->getRelates();
        $productForm = new ProductForm($departments[1],$product);
        $categoryService = new CategoryService();
        $categoriesXml = $categoryService->getAllCategoriesXml();
        $categoryProducts = $productService->getCategoryProductsByProductId($productId);
        $this->view->id = $productId;
        //$this->view->flag = 0;
        $this->view->form = $productForm;
        $this->view->productItems = $productItems;
        $this->view->categoryXml = $categoriesXml;
        $this->view->categoryProducts = $categoryProducts;
        $this->view->metadataSet = $metadataSet;
        $this->view->productMetadatas = $productMetadatas;
        $this->view->itemMetadatas = $itemMetadatas;
        $itemMetadatasById = array();
        if(!empty($itemMetadatas)){
        	foreach($itemMetadatas as $itemMetadataTemp){
        		$itemMetadatasById[$itemMetadataTemp['id']] = $itemMetadataTemp;
        	}
        }
        $this->view->itemMetadatasById = $itemMetadatasById;
        $this->view->productMetadataValues = $productMetadataValues;
        $this->view->metadataSetId = $setId;
    }

    public function subeditAction() {
        $productId = $this->_getParam('id');
        $productService = new ProductService();
        $categoryService = new CategoryService();
        $departments = $productService->getDepartments();
        $relates = $productService->getRelates();
        $product = array("id" => $productId);
        $productForm = new ProductForm($departments[1], $product);
        if(!$productForm->isValid($_POST)) {
            $setId = trim($_POST['metadataSetId']);
            //metadata set
            $metadataSet = $productService->getSetById($setId);
            //product metadata
            $productMetadatas = $productService->getMetadataBySet($setId, 1);
            //item metadata
            $itemMetadatas = $productService->getMetadataBySet($setId, 2);
            //product metadata value
            $productMetadataValues = $productService->getProductMetatdataValue($productId);
            $categoriesXml = $categoryService->getAllCategoriesXml();
            $categoryProducts = $productService->getCategoryProductsByProductId($productId);
            $this->view->categoryXml = $categoriesXml;
            $this->view->categoryProducts = $categoryProducts;
            $this->view->form = $productForm;
            $this->view->metadataSet = $metadataSet;
            $this->view->productMetadatas = $productMetadatas;
            $this->view->itemMetadatas = $itemMetadatas;
            $this->view->productMetadataValues = $productMetadataValues;
            $this->view->metadataSetId = $setId;
            return $this->render('edit');
        }
        //edit product items
        $productService->editProduct($productForm,$_POST);
        $this->_redirector->gotoUrl('inventory/product');
    }

    public function deleteAction() {
        $productId = $this->_getParam('id');
        $productService = new ProductService();
        $productService->deleteProduct($productId);
        $this->_redirector->gotoUrl('inventory/product');
    }

    public function deletesomeAction() {
        $idsStr = HttpUtil::getPostValue("selectIds");
        $ids = explode(",",$idsStr);
        $productService = new ProductService();
        $productService->deleteAllProduct($ids);
        $this->_redirector->gotoUrl('inventory/product');
    }

    public function addattributeAction() {
        $productId = $this->_getParam('id');
        $attributeForm = new AttributeForm();
        $attributeForm->getElement('productId')->setValue($productId);
        $this->view->form = $attributeForm;
    }

    public function subadditemsAction() {
        $productService = new ProductService();
        $attributeForm = new AttributeForm();
        if(!$attributeForm->isValid($_POST)) {
            $this->view->form = $attributeForm;
            return $this->view->render('addAttribute');
        }
        $productId = $attributeForm->getValue('productId');
        $attributes = array();
        $names = array();

        for($i=1; $i<6; $i++) {
            $name = $attributeForm->getValue('attribute' . $i);
            if(!empty($name)) {
                $names[$i] = $name;
                $attributes[$names[$i]] = explode(",", $attributeForm->getValue('value' . $i));
            }
        }
        $productService->addItems($productId, $attributes);
        $url = 'inventory/product/listitem/id/' . $productId;
        $this->_redirector->gotoUrl($url);
    }

    public function listitemAction() {
        $productId = $this->_getParam('id');
        $productService = new ProductService();
        $items = $productService->listItems($this->view, $_POST, $productId);
        $this->view->items = $items;
    }

    public function additemAction() {
        $productId = $this->_getParam('pid');
        $productService = new ProductService();
        $product = $productService->getProductById($productId);
        $productTitle = $product['title'];
        $itemForm = new ItemForm();
        $itemForm->getElement('productId')->setValue($productId);
        $this->view->form = $itemForm;
        $this->view->title = $productTitle;
    }

    public function saveitemAction() {
        $productService = new ProductService();
        $itemForm = new ItemForm();
        if(!$itemForm->isValid($_POST)) {
            $id = $itemForm->getValue('id');
            $productId = $itemForm->getValue('productId');
            $product = $productService->getProductById($productId);
            $productTitle = $product['title'];
            $this->view->form = $itemForm;
            $this->view->title = $productTitle;
            if(empty($id)) {
                return $this->render('additem');
            } else {
                return $this->render('edititem');
            }
        }
        $id = $itemForm->getValue('id');
        $productId = $itemForm->getValue('productId');
        if(empty($id)) {
            $productService->addItem($itemForm);
        } else {
            $productService->updateItem($itemForm);
        }
        $url = 'inventory/product/listitem/id/' . $productId;
        $this->_redirector->gotoUrl($url);


    }

    public function edititemAction() {
        $id = $this->_getParam('id');
        $productService = new ProductService();
        $item =  $productService->getItemById($id);
        $itemForm = new ItemForm($item);
        $productId = $item['product_id'];
        $product = $productService->getProductById($productId);
        $productTitle = $product['title'];
        $this->view->form = $itemForm;
        $this->view->title = $productTitle;
    }

    public function delitemsAction() {
        $productId = $this->_getParam('pid');
        $idsStr = HttpUtil::getPostValue("selectIds");
        $ids = explode(",",$idsStr);
        $productService = new ProductService();
        $productService->deleteItems($ids);
        $url = 'inventory/product/listitem/id/' . $productId;
        $this->_redirector->gotoUrl($url);
    }

    public function searchrelateAction() {
        $this->_helper->layout->disableLayout();
        $productService = new ProductService();
        $products = $productService->getRelateProduct($this->view, $_POST);
        $this->view->products = $products;
    }

    public function searchitemAction(){
        $from = $this->_getParam("from");
        $this->_helper->layout->disableLayout();
        $productService = new ProductService();
        $items = $productService->searchItem($this->view, $_POST,$from);
        $this->view->items = $items;
    }

    public function uniquetitleAction(){
        $productService = new ProductService();
        $result = $productService->unique("products", "title",HttpUtil::getPostString("v"),HttpUtil::getPostString("id"));
        if($result == true){
            echo "1";
        }else{
            echo "0";
        }
        exit();
    }

    public function uniqueurltitleAction(){
        $productService = new ProductService();
        $result = $productService->unique("products", "url_title",HttpUtil::getPostString("v"),HttpUtil::getPostString("id"));
        if($result == true){
            echo "1";
        }else{
            echo "0";
        }
        exit();
    }
    
    //ajax function to edit the item image
    public function edititemimageAction(){
    	$this->_helper->layout->disableLayout();
        $itemId = $this->_getParam('id');
        $pid = $this->_getParam('pid');
        $productService = new ProductService();
        $itemImages = $productService->getItemImageByItemId($itemId);
        $this->view->itemImages = $itemImages;
        $this->view->itemId = $itemId;
        $this->view->pid = $pid;
    }
    
    //ajax function to set the image attribute
    public function editimageinfoAction(){
    	$this->_helper->layout->disableLayout();
        $pid = $this->_getParam("pid");
        $itemId = $this->_getParam("itemId");
        $productService = new ProductService();
        $itemImages = $productService->getItemImageByItemId($itemId);
        $this->view->itemImages = $itemImages;
        $this->view->itemId = $itemId;
        $this->view->pid = $pid;
    }
    
    public function deleteimageAction(){
    	$imageId = $this->_getParam('id');
        //akimimi_common
        $thumbnail = new Thumbnail();
        $thumbnail->removeProductImageById($imageId);
        echo $imageId;
        exit;
    }
    
    //设置图片为默认的产品图片或图片显示的顺序
    public function editimageattributeAction(){
    	$itemId = HttpUtil::getPostString("itemId");
    	$imageIds = HttpUtil::getPostString("imageIds");
        $sorts = HttpUtil::getPostString("sorts");
        $defaultImages = HttpUtil::getPostString("defaultImages");
        $imageIdArray = explode(",", $imageIds);
        $sortArray = explode(",", $sorts);
        $productService = new ProductService();
        $productService->editImageAttribute($itemId, $imageIdArray, $sortArray, $defaultImages);
        echo 1;
        exit;
    }
    
    //判断是否设置了默认图片
    public function issetdefaultimageAction(){
    	$itemId = $this->_getParam("itemId");
    	$productService = new ProductService();
        $result = $productService->isSetDefaultImage($itemId);
    	$data = array("isDefaultImage"=>$result);
        echo json_encode($data);
        exit;
    }
    
    public function uploadimageAction(){
    	$this->_helper->layout->disableLayout();
    	$pid = $this->_getParam("pid");
    	$itemId = $this->_getParam("itemId");
    	$imageInfo = array("pid" => $pid, "itemId" => $itemId);
        $this->view->imageInfo = $imageInfo;
    }
    
    public function submituploadAction(){
    	$this->_helper->layout->disableLayout();
    	$itemId = HttpUtil::getPostValue("uploadItemId");
    	$productId = HttpUtil::getPostValue("uploadProductId");
    	$isDefaultImage = HttpUtil::getPostValue("defaultImage");
    	$sortOrder = HttpUtil::getPostValue("sortOrder");
    	$imagePath = "";
    	$imageName = "";
    	// 初始化ssh服务
    	$ssh = new SshService();
    	$ssh->connect();
    	for($i = 0; $i < 10; $i++){
    		$textName = 'uploadFileName_'.$i;
    		$result = BaseUtil::uploadFile(Zend_Registry::get('temp_folder'), $textName);
	    	if( isset($result['file_path']) && !empty($result['file_path']) ){
	            $imageName = $result['file_path'];
	            $imagePath = Zend_Registry::get('temp_folder')."/".$imageName;
	            
	            if ($this->_enableSsh)
	            {
	                // 上传至图片服务器
    	            $ssh->sftp_put($imagePath, $imagePath);
    	            $ssh->ssh2_exec("/opt/akimimi_common/uploaditemimage.sh "
    	                ."\\\"$productId\\\",\\\"$itemId\\\","
    	                ."\\\"$sortOrder[$i]\\\",\\\"$isDefaultImage[$i]\\\","
    	                ."\\\"$imagePath\\\" "
    	                ."$imageName\.php");	                
	            }
	            else
	            {
    	            //引用akimimi_common文件
    	            $thumbnail = new Thumbnail();
    	            $thumbnail->uploadOneProductImage($productId, $itemId, $sortOrder[$i], $isDefaultImage[$i], $imagePath);
	            }
	        }
    	}
    	$this->view->itemId = $itemId;
    	$this->view->productId = $productId;
    }
    
    
    
}